var http = require('http');
var azure = require('azure');

    
var ServiceClient = azure.ServiceClient;
var client = azure.createTableService('UseDevelopmentStorage=true');
//    var client = azure.createTableService('DefaultEndpointsProtocol=http;AccountName=jakartastore;AccountKey=uBiNc5j2tfRBIhjPWQbCBwWJFBfqj5+IgmV5stiXXKFPeAwZiS6Mx1uc8Yg9TJdw/2MHMmrpVlOzCcKIEPfO+g==');

http.createServer(function (req, res) {
    
    if(req.url=='/'){
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end('Hello, world!');
    }else
    if(req.url=='/createtask'){
     
          client.createTableIfNotExists("tasks", function (err) {
              if (!err) {
                var item = {
                  PartitionKey: 'pik',
                  RowKey: '1',  
                  name: 'Learning basic statistics',
                  category: 'Study',                  
                  date: new Date(),              
                  completed: false
                };

                client.insertOrReplaceEntity("tasks", item, function (err) {
                    if(!err){                        
                        res.writeHead(200, { 'Content-Type': 'text/html' });
                        res.end('ok!');
                    }else{
                       res.writeHead(200, { 'Content-Type': 'text/html' });
                        res.end(JSON.stringify(err));
                    }
                    
                });
              } else {
                    res.write(err);
                    res.end();
              }
         });
    }

    else
    if(req.url=='/listtask'){        

        var TableQuery = azure.TableQuery;
        var query = TableQuery.select().from('tasks');       
        
        client.queryEntities(query, function(err,taskList){

            if(!err){                                               
                  res.writeHead(200, { 'Content-Type': 'text/html' });
                  res.end(JSON.stringify(taskList));
            }else{
                  res.writeHead(200, { 'Content-Type': 'text/html' });
                  res.end(JSON.stringify(err));
            }
        });
                         
    }
    
}).listen(process.env.PORT || 8080);